<template>
	<div class="container">
    <header-compent activeName="userlist" :agent="agent" :usertype="usertype" :is_manager="is_manager"></header-compent>
      <kf-box-compent :active_status="active_status" :wait_active_cnt="wait_active_cnt"></kf-box-compent>
    	<div class="page-header"><div  class="el-page-header"><div class="el-page-header__content">人员管理</div></div></div>
    	
    	<div class="page-body">
    		<el-tabs type="border-card" v-model="activeName" @tab-click="handleClick" >
    		
			  <el-tab-pane name="use" label="已使用人员">
			  	 <div class="selectBox mb20 flex a-item-center justfy-start">
					<el-button size="mini" type="primary" class="ml10" @click="payUserAll">批量激活</el-button>
				 </div>
			  	 <el-table
			  	 	ref="multipleuserTable"
				    :data="userList"
				    stripe
				    style="width: 100%"
				    @selection-change="handleSelectionUseChange"
				    >
				    <el-table-column
				      type="selection"
				      :selectable ="enableUseSelect"
				      width="55">
				    </el-table-column>
				   	<el-table-column
				      prop="qy_userid"
				      label="姓名">
				      <template slot-scope="scope">
					      <ww-open-data type="userName" :openid="scope.row.qy_openid" />
					      <el-tag v-if="scope.row.me == 1" size="mini" class="ml10">本人</el-tag>
				      </template>
				    </el-table-column>
				    <el-table-column
				      prop="username"
				      label="昵称"
				      >
				    </el-table-column>
				    <el-table-column
				      prop="avatar"
				      label="头像"
				     >
				      <template slot-scope="scope">
				        <img :src="scope.row.avatar" width="30px"/>
				      </template>
				    </el-table-column>
				    <el-table-column
				      prop="active_status"
				      label="激活状态"
				     >
				      <template slot-scope="scope">
				       	<span v-if="scope.row.active_status==0">
					    	{{scope.row.wait_active_cnt==0?'未激活':'激活中，等待专员激活'}}
					    </span>
					    <span v-if="scope.row.active_status==1">已激活</span>
				      </template>
				    </el-table-column>
				    <el-table-column
				      prop="active_status"
				      label="操作"
				      width="100px"
				     >
				      <template slot-scope="scope">
				      	 <el-button size="mini" type="primary" v-if="scope.row.active_status==0 &&scope.row.wait_active_cnt==0" @click="payFromUse(scope.row)">去激活</el-button>
				      	 <el-button size="mini" type="primary" disabled v-if="scope.row.active_status==0 &&scope.row.wait_active_cnt==1 ">激活中</el-button>
				       	  <el-button size="mini" type="success" disabled v-if="scope.row.active_status==1">已激活</el-button>
				      </template>
				    </el-table-column>
			
				  </el-table>
				  <div class="mt20 mb20">
				  	
				  
				    <el-pagination
				      @size-change="handleSizeChange"
				      @current-change="handleCurrentChange"
				      :current-page="query.page"
				      :page-sizes="[10, 20, 30, 50]"
				      :page-size="query.limit"
				      layout="total, sizes, prev, pager, next"
				      :total="total">
				    </el-pagination>
				    </div>
			  </el-tab-pane>
			  <el-tab-pane name="department" label="内部人员列表">
			  	<div class="selectBox mb20 flex a-item-center justfy-start">
			  		 <el-select v-model="departmentID" placeholder="请选择部门"   size="mini"  @change="fnDepartmentListChange" clearable>
					    <el-option
					      v-for="item in departmentList"
					      :key="item.id"
					      
					      :label="'部门ID:'+item.id"
					      :value="item.id">
						      <span >
						      	<span>部门ID:{{item.id}}</span>
						      	<span style="color: #999999; font-size: 12px;">
						      		（
						      		<ww-open-data type="departmentName" :openid="item.id" />
						      		）
						      	</span>
					
						      </span>
					    
					    </el-option>
					  </el-select>
					  
					  <el-button size="mini" type="primary" class="ml10" @click="payAll">批量激活</el-button>
			  	</div>
			  	 <el-table
			  	 	ref="multipleTable"
				    :data="departmentUserList"
				    stripe
				    style="width: 100%"
				    @selection-change="handleSelectionChange">
				    <el-table-column
				      type="selection"
				      :selectable ="enableSelect"
				      width="55">
				    </el-table-column>
				   	<el-table-column
				      prop="name"
				      label="姓名">
				      <template slot-scope="scope">
				      <ww-open-data type="userName" :openid="scope.row.name" /> <el-tag v-if="scope.row.me == 1" size="mini" class="ml10">本人</el-tag>
				      </template>
				    </el-table-column>
				 
				    <el-table-column
				      prop="avatar"
				      label="所属部门ID"
				     >
				      <template slot-scope="scope">
				      	
				      	<div v-for="item in scope.row.department">
				      		ID：{{item}}—<span style="color: #999999; font-size: 12px;">（<ww-open-data type="departmentName" :openid="item == 0?'1':item" />）</span>
				      	</div>
				       
				      </template>
				    </el-table-column>
				    <el-table-column
				      prop="active_status"
				      label="激活状态"
				     >
				      <template slot-scope="scope">
				       	<span v-if="scope.row.active_status==0">
					    	{{scope.row.wait_active_cnt==0?'未激活':'激活中，等待专员激活'}}
					    </span>
					    <span v-if="scope.row.active_status==1">已激活</span>
				      </template>
				    </el-table-column>
				    
				     <el-table-column
				      prop="active_status"
				      label="操作"
				      width="100px"
				     >
				      <template slot-scope="scope">
				      	 <el-button size="mini" type="primary" v-if="scope.row.active_status==0 &&scope.row.wait_active_cnt==0" @click="payFromDepart(scope.row)">去激活</el-button>
				      	 <el-button size="mini" type="primary" disabled v-if="scope.row.active_status==0 &&scope.row.wait_active_cnt==1 ">激活中</el-button>
				       	  <el-button size="mini" type="success" disabled v-if="scope.row.active_status==1">已激活</el-button>
				      </template>
				    </el-table-column>
			
				  </el-table>
			  </el-tab-pane>
		
			</el-tabs>
    		
    		
    	</div>
    	
    	<el-dialog title="微信扫码支付" :visible.sync="dialogTableVisible" width="370px" @close="closePay">
	    	<div class="qr-code">
		        <!--<div class="header">支付</div>-->
		        <div class="subtitle">
		          {{`购买许可账号，需要支付${price}元`}}
		        </div>
		        <vue-qr
		            ref="Qrcode"
		            :text="pay_url"
		            :margin="0"
		            colorDark="#333333"
		            colorLight="#ffffff"
		            :logoSrc="icon"
		            :logoScale="1"
		            :size="160"
		          ></vue-qr>
		        <div class="tips flex justify-center a-item-center">
		          <img src="@/assets/image/wx.png" alt="" />
		          <p>使用微信扫码付款</p>
		        </div>
		    </div>
    	</el-dialog>
    	
    	<el-dialog title="如何授权应用权限?" :visible.sync="dialogHelpVisible" width="970px">
	    	<div class="help_title">
		       
		        
		        <div class="subtitle big">
                                第一步：管理员登录企业微信后台：<a href="https://work.weixin.qq.com/wework_admin/frame#profile" target="_blank">点击登录</a>
		        </div>
		     	<div class="subtitle">
		        1.管理员登录后台后，点击打开我的企业，2.打开权限管理，3.选择人员管理，4.配置管理员，5.应用与小程序权限添加“群互动”
		        </div>
		       
		        
		        <div> <img src="../assets/image/help1.png" width="900px" style="margin: 0 auto; display: block;"/></div>
		        <div class="subtitle big">
		                第二步.管理员配置应用权限：
		        </div>
		        <div class="subtitle">
		        1.管理员进入应用管理，2.选择应用，3.找到群互动打开</div>
		        <div> <img src="../assets/image/help2.png" width="900px" style="margin: 0 auto; display: block;"/></div>
		         <div class="subtitle">
		        4.应用授权方式，选择管理员授权使用，配置可见范围，选择全部5.查看授权信息，6.查看组织架构信息点击前往授权，7.管理员扫码后点击同意授权，8点击同意
		        </div>
		        <div> <img src="../assets/image/help3.png" width="900px" style="margin: 0 auto; display: block;"/></div>
		        <div> <img src="../assets/image/help4.png" width="900px" style="margin: 0 auto; display: block;"/></div>
		        <div> <img src="../assets/image/help5.png" width="900px" style="margin: 0 auto; display: block;"/></div>
		        <div class="subtitle big">
		                第三步.授权完成后，登出并重新登录。
		        </div>
		       
		      
		    </div>
		     <div slot="footer" class="dialog-footer">
			    <el-button @click="dialogHelpVisible = false">取 消</el-button>
			    <el-button type="primary" @click="goSetting">去配置</el-button>
			 </div>
    	</el-dialog>
    	
    	<el-dialog
		  title="账号许可说明"
		  :visible.sync="dialogAccountVisible"
		  width="1000px"
		  >
		  <iframe src="https://open.work.weixin.qq.com/wwopen/common/readDocument/38829" width="960px" height="758px" frameborder="0" border="no"></iframe>
		  <span slot="footer" class="dialog-footer">
		    <el-button type="primary" @click="dialogAccountVisible = false">关 闭</el-button>
		  </span>
		</el-dialog>

    	
    </div>
</template>

<script>
import { getUserList,postGetOrderPrice,postGetOrder,postCheckOrder,postDepartmentList, postDepartmentUserList} from "../api/index";	
import Cookies from "js-cookie";
import HeaderCompent from "./header.vue";
import KfBoxCompent from "./kefubox.vue";
import vueQr from "vue-qr";
import icon from '@/assets/image/wepay.png'

export default {
  name: 'index',
   components: {
	HeaderCompent,vueQr,KfBoxCompent
  },
  data () {
    return {
	    isSending:false,
	    userList:[],
	    dialogTableVisible:false,
	    pay_url:'',
	    price:0,
	    icon:icon,
	    order_id:'',
	    timer:'',
	    query:{
	    	page:1,
	    	limit:10
	    },
	    total:0,
	    departmentList:[],
	    departmentID:'',
	    departmentUserList:[],
	    activeName:"use",
	    user_list:[],
	    agent:Cookies.get('agent') || '0',
	    usertype:Cookies.get('usertype') || '0',
	    dialogHelpVisible:false,
	    
	    active_status:'0',
	    wait_active_cnt:'0',
	    dialogAccountVisible:false,
      is_manager: Cookies.get('is_manager') || 0,
	    
    }
  
  },
  methods:{

  	goSetting(){
  		location.href='https://work.weixin.qq.com/wework_admin/frame#profile';
  	},
  	payUserAll(){
		if(this.user_list.length == 0 ){
			 this.$message.error('请选择需要激活的人员');
		}
		else{
			this.fnGetOrderPrice();
			
		}
  	},
  	handleSizeChange(e){
  		this.query.limit = e;
  		this.fnGetUserList();
  	},
  	handleCurrentChange(e){
  		this.query.page = e;
  		this.fnGetUserList();
  		
  	},
  	fnDepartmentListChange(){
  	
  		this.fnGetDepartmentUserList();
  	},
  	payFromUse(v){
  		this.user_list=[{
			userid:v.qy_userid,
			open_userid:v.qy_openid
		}]
  		console.log(this.user_list);
  		this.fnGetOrderPrice();
  	},
  	payFromDepart(v){
  		this.user_list=[{
			userid:v.userid,
			open_userid:v.open_userid
			}]
  		console.log(this.user_list);
  		this.fnGetOrderPrice();
  	},
  	payAll(){
  		if(this.user_list.length == 0 ){
  			 this.$message.error('请选择需要激活的人员');
  			
  			 
  		}
  		else{
  			this.fnGetOrderPrice();
  			
  		}
  	},
  	enableUseSelect(row,index){
  		if(row.active_status == 0 && row.wait_active_cnt == 0 ){
  			return true;
  			
  		}
  		else{
  			return false;
  		}
  	},
  	enableSelect(row,index){
  	
  		if(row.active_status == 0 && row.wait_active_cnt == 0 ){
  			return true;
  			
  		}
  		else{
  			return false;
  		}
  	},
  	handleSelectionUseChange(value){
  		var arr = [];
  		value.forEach((v,i)=>{
  			arr.push({
	    		userid:v.qy_userid,
	    		open_userid:v.qy_openid
    		});
  		})
  		this.user_list=arr;
  	},
  	handleSelectionChange(value){
  		var arr = [];
  		value.forEach((v,i)=>{
  			arr.push({
	    		userid:v.userid,
	    		open_userid:v.open_userid
	    		});
  		})
  		this.user_list=arr;
  	},
  	handleClick(e){
		
  		if(e.name == 'department'){
  			if(this.agent == 0){
  				this.$message.error('未获得应用权限，请先授权');
  				
  				 setTimeout(()=>{
	  			 	this.activeName = 'use';
	  			 	this.dialogHelpVisible = true;
	  			 },1000)
  			}
  			else{
  				this.user_list=[];
  				this.active_status='0';
	    		this.wait_active_cnt='0';
  				this.fnGetDepartmentList();
  				this.fnGetDepartmentUserList();
  			}

  		}
  		else if(e.name == 'use'){
  			this.user_list=[];
  			this.active_status='0';
	    	this.wait_active_cnt='0';
  			this.fnGetUserList();
  		}
  	},
  	fnGetDepartmentUserList(){
  		var department_id = this.departmentID ==''?1:this.departmentID;
	  	var params = {
	       department_id:department_id
	    }
	   	 postDepartmentUserList(params
	     ).then((res) => {
	    
	        let { msg, code, data } = res.data;
	      	
			if(code == 200){
				this.departmentUserList = data;
			}
			this.departmentUserList.forEach((v,i)=>{
				if(v.active_status == 1){
					this.active_status = 1;
				}
				if(v.wait_active_cnt == 1){
					this.wait_active_cnt = 1;
				}
			})
	
	        
	        
	      },reject=>{
	      	 this.isSending = false;
	      	 let { msg, code, data } = reject.data;
	      	 if(code == 401){
	      	 	Cookies.remove('token');
	      	 	this.$router.push('/login')
	      	 }
	      	 
	      });
  	},
  	//获取部门列表
  	fnGetDepartmentList(){
 
   	  var params = {
       
      }
   	 postDepartmentList(params
     ).then((res) => {
    
        let { msg, code, data } = res.data;
      	
		if(code == 200){
			if(data){
				this.departmentList = data;
			}
			else{
				this.$message.error('未获得应用权限，请先授权');
  				
				setTimeout(()=>{
	  			 	this.activeName = 'use';
	  			 	this.dialogHelpVisible = true;
	  			},1000)
			}
		}

        
        
      },reject=>{
      	 this.isSending = false;
      	 let { msg, code, data } = reject.data;
      	 if(code == 401){
      	 	Cookies.remove('token');
      	 	this.$router.push('/login')
      	 }
      	 
      });
  	},
  	//获取用户列表
   	fnGetUserList(){
   		if(this.isSending == true){
   			console.log('请稍等');
   			return false;
   		}
   		var params = {
       
      }
   		this.isSending = true;
   		getUserList(this.query
     ).then((res) => {
     
      	this.isSending = false;
        let { msg, code, data } = res.data;
      	
		if(code == 200){
		
			this.userList = data.list;
			this.total = data.total;
			this.userList.forEach((v,i)=>{
				if(v.active_status == 1){
					this.active_status = 1;
				}
				if(v.wait_active_cnt == 1){
					this.wait_active_cnt = 1;
				}
			})
		}

        
        
      },reject=>{
      	 this.isSending = false;
      	 let { msg, code, data } = reject.data;
      	 if(code == 401){
      	 	Cookies.remove('token');
      	 	this.$router.push('/login')
      	 }
      	 
      });
   	},
   	fnGetOrderPrice(){
   		var self = this;
   		if(this.isSending == true){
   			console.log('请稍等');
   			return false;
   		}
   		var params = {
	       amount:this.user_list.length,
	       months:process.env.PAY_MONTH
	    }
   		
   		this.isSending = true;
   		postGetOrderPrice(params).then((res) => {
	      	this.isSending = false;
	        let { msg, code, data } = res.data;
	        if(code == 200){
	        	 this.price = data.price/100;
	        	 this.isSending = false;
	        	const h = this.$createElement;
		        this.$msgbox({
		          customClass:'myMesbox',
		          title: '购买并激活',
		          message: h('div', {attrs:{'style':'max-height: calc(100vh - 200px);overflow-y: auto;'}},  [
		            h('div', {attrs: {'style':'margin:10px 0;line-height: 20px;display: flex;'}}, [
		              	 h('span', null, '已过90天企微官方免费试用期，需要购买【许可账号】'),
		              	 h('img', {attrs: {'src': 'https://static.ccxia.cn/Uploads/lottery/2301/63b636788afb0.png','width':'20px','style':'margin:0px 5px 0 0;cursor: pointer;'},on: {
				              click() {
				              	  debugger;
				              	  self.dialogAccountVisible = true;
//				                 self.$alert('<iframe src="https://open.work.weixin.qq.com/wwopen/common/readDocument/38829" width="960px" height="758px" frameborder="0" border="no"></iframe>', '许可账号', {
//						          dangerouslyUseHTMLString: true,
//						          customClass:'myMesbox2',
//						        });
				              }
				            }},''),
		              	 h('span', null, '才能继续使用。')
		            ]),
		             h('div', null,[
			              h('span', null, '您已选择购买'),
			              h('span', {attrs:{'style':'color:red;padding:0 5px;'}}, this.user_list.length),
			              h('span', null, '个许可，需要支付：'),
			              h('span', {attrs:{'style':'color:red;padding:0 5px;'}}, this.price),
			              h('span', null, '元。')
		             ]),
		            h('div', {attrs: {'style':'margin:10px 0;'}}, '购买后，会有专员为您激活（工作日：9点~18点）。'),
		            h('div', {attrs: {'style':'margin:50px 0 10px;color:#999999;'}}, '以下是购买的价格详细说明：'),
		            h('img',  {attrs: {'src': 'https://static.ccxia.cn/Uploads/lottery/2301/63b6641046741.jpg','width':'662px','style':'margin:5px auto;display:block;'}},''),
		            h('div', {attrs: {'style':'margin:10px 0;color:#999999;'}}, '在此价格上收取1%的手续费。'),
		            h('div', {attrs: {'style':'margin:10px 0;color:#999999;'}}, '价格计算方式，例如购买10个账号：'),
		            h('div', {attrs: {'style':'margin:10px 0;color:#999999;'}}, '1~5个账号区间5个（5元/账号/年），需支付 5x5 = 25元，6~200个账号区间5个（4元/账号/年），需支付 5x4 = 20元，共45元。 '),
		            h('div', {attrs: {'style':'margin:10px 0;color:#999999;'}}, '其中1%的手续费，45*0.01 = 0.45元。') ,
		            h('div', {attrs: {'style':'margin:10px 0;color:#999999;'}}, '共需支付45+0.45 = 45.45元 。 ') ,
		            h('div', {attrs: {'style':'margin:10px 0;color:#999999;'}}, '如有疑问，请扫码咨询客服 。 ') ,
		            h('img',  {attrs: {'src': 'https://static.ccxia.cn/Uploads/lottery/2301/63b647a7c0b7e.png','width':'100px','style':'margin:5px 0;'}},''),
		            
		            
		            

//		            h('i', { style: 'color: teal' }, 'VNode')
		          ]),
		          showCancelButton: true,
		          confirmButtonText: '去支付',
		          confirmButtonClass:'originBtn',
		          cancelButtonText: '取消'
		        }).then(action => {
		          if (action === 'confirm') {
		            	this.fnGetOrder();
		            } else {
			            this.user_list=[];
			          	this.$refs.multipleuserTable.clearSelection();
						this.$refs.multipleTable.clearSelection();
		            }
		        }).catch((err) => {
		          this.$message({
		            type: 'info',
		            message: '已取消'
		          });          
		        });;
//	        	 this.$alert('激活需要先支付'+(data.price/100)+'元，付款后，会有专员为您激活（工作日：9点~18点）是否需要激活？', '激活提醒', {
//		          confirmButtonText: '去支付',
//		          callback: action => {
//		          	if(action=='confirm'){
//		          		this.fnGetOrder();
//		          	}
//		          	else{
//		          		this.user_list=[];
//		          		this.$refs.multipleuserTable.clearSelection();
//						this.$refs.multipleTable.clearSelection();
//		          	}
//		          	
//		          
//		            
//		          }
//		        });
	        }
	  
	    },reject=>{
	      	 this.isSending = false;
	      	 let { msg, code, data } = reject.data;
	      	 if(code == 401){
	      	 	Cookies.remove('token');
	      	 	this.$router.push('/login')
	      	 }
	    });
   	},
   	fnGetOrder(){
   		var self = this;
   		if(this.isSending == true){
   			console.log('请稍等');
   			return false;
   		}
   		var params = {
	    	amount:this.user_list.length,
	    	months:process.env.PAY_MONTH,
	    	user_list:this.user_list,
	    }
   	
   		this.isSending = true;
   		postGetOrder(params
     ).then((res) => {
     
      	this.isSending = false;
        let { msg, code, data } = res.data;

		if(code == 200){
			this.pay_url = data.pay_url;
			this.order_id = data.order_id;
			this.dialogTableVisible = true;
			self.timer = setInterval(()=>{
				self.checkOrder();
			},1000)
		}

        
        
      },reject=>{
      	 this.isSending = false;
      	 let { msg, code, data } = reject.data;
      	 if(code == 401){
      	 	Cookies.remove('token');
      	 	this.$router.push('/login')
      	 }
      	 
      });
   	},
   	checkOrder(){
   		var self = this;
   		if(this.isSending == true){
   			console.log('请稍等');
   			return false;
   		}
   		var params = {
	    	order_id:this.order_id
	    }
   		this.isSending = true;
   		postCheckOrder(params
     ).then((res) => {
     
      	this.isSending = false;
        let { msg, code, data } = res.data;

		if(code == 200){
			if(data.status != 1){
				clearInterval(self.timer);
				self.dialogTableVisible = false;
				if(self.activeName == 'department'){
		  			
		  			
	  				this.user_list=[];
	  				this.fnGetDepartmentUserList();
		  			
		  		}
		  		else if(self.activeName  == 'use'){
		  			this.user_list=[];
		  			this.fnGetUserList();
		  		}
//				self.fnGetUserInfo();

				if(data.status == 2){
					console.log('已付款')
				}
				else if(data.status == 3){
					console.log('付款失败')
				}
				else if(data.status == 4){
					console.log('已退款')
				}
			}
			else{
				console.log('继续check')
			}
		}

      },reject=>{
      	 this.isSending = false;
      	 clearInterval(self.timer);
		 self.dialogTableVisible = false;
      	 let { msg, code, data } = reject.data;
      	 if(code == 401){
      	 	
      	 	Cookies.remove('token');
      	 	this.$router.push('/login')
      	 }
      	 
      });
   	},
   	closePay(){
   		clearInterval(this.timer);
   	},
  },
  created(){
  	 console.log(process.env.BASE_API)
  	 console.log(process.env.PAY_MONTH)
  	  this.token = Cookies.get('token');
  	  if(!this.token){
  	  	this.$router.push('/login');
  	  }
  	  else{
  	  	this.fnGetUserList();
	  	
  	  }
	
  },
  mounted(){

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped  type="text/scss" lang="scss" >

	.item{
		margin: 20px auto;
	}
	.qr-code {
	  text-align: center;
	  .subtitle {
	    padding: 15px 0 30px;
	  }
	  .tips {
	    padding-top: 25px;
	    img{
	    	margin-right: 10px;
	    }
	  }
	}
	.help_title {
	  text-align: left;
	  .subtitle {
	    padding: 10px;
	    &.big{
	    	font-size: 16px;
	    	font-weight: bold;
	    	margin-top: 20px;
	    }
	  }
	  .tips {
	    padding-top: 25px;
	    img{
	    	margin-right: 10px;
	    }
	  }
	}

</style>
